var CreatedOKLodopObject, CLodopIsLocal, CLodopJsState;

//====判断是否需要安装CLodop云打印服务器:====
function needCLodop() {
    try {
        var ua = navigator.userAgent;
        if (ua.match(/Windows\sPhone/i))
            return true;
        if (ua.match(/iPhone|iPod|iPad/i))
            return true;
        if (ua.match(/Android/i))
            return true;
        if (ua.match(/Edge\D?\d+/i))
            return true;

        var verTrident = ua.match(/Trident\D?\d+/i);
        var verIE = ua.match(/MSIE\D?\d+/i);
        var verOPR = ua.match(/OPR\D?\d+/i);
        var verFF = ua.match(/Firefox\D?\d+/i);
        var x64 = ua.match(/x64/i);
        if ((!verTrident) && (!verIE) && (x64))
            return true;
        else if (verFF) {
            verFF = verFF[0].match(/\d+/);
            if ((verFF[0] >= 41) || (x64))
                return true;
        } else if (verOPR) {
            verOPR = verOPR[0].match(/\d+/);
            if (verOPR[0] >= 32)
                return true;
        } else if ((!verTrident) && (!verIE)) {
            var verChrome = ua.match(/Chrome\D?\d+/i);
            if (verChrome) {
                verChrome = verChrome[0].match(/\d+/);
                if (verChrome[0] >= 41)
                    return true;
            }
        }
        return false;
    } catch (err) {
        return true;
    }
}

//====页面引用CLodop云打印必须的JS文件：====
if (needCLodop()) {
	var head = document.head || document.getElementsByTagName("head")[0] || document.documentElement;
	var oscript = document.createElement("script");
	
	var ishttps = 'https:' == document.location.protocol ? true: false;
    var url = window.location.host;
	
	if(ishttps){
		oscript = document.createElement("script");
		//oscript.src ="https://localhost:8443/CLodopfuncs.js"; 
		oscript.src ="https://localhost:8443/CLodopfuncs.js";
		console.log(oscript);
		head.insertBefore(oscript,head.firstChild);
	}else{
		oscript.src ="http://localhost:8000/CLodopfuncs.js?priority=1";
		head.insertBefore(oscript,head.firstChild);
	
		//引用双端口(8000和18000）避免其中某个被占用：
		oscript = document.createElement("script");
		oscript.src ="http://localhost:18000/CLodopfuncs.js?priority=0";
		head.insertBefore(oscript,head.firstChild);
	}
};

//==加载引用CLodop的主JS,用双端口8000和18000(以防其中一个被占):==
function loadCLodop() {
    if (CLodopJsState == "loading" || CLodopJsState == "complete") return;
    CLodopJsState = "loading";
    var head = document.head || document.getElementsByTagName("head")[0] || document.documentElement;
    var JS1 = document.createElement("script");
    var JS2 = document.createElement("script");
    JS1.src = "http://localhost:8000/CLodopfuncs.js?priority=1";
    JS2.src = "http://localhost:18000/CLodopfuncs.js";
    JS1.onload  = JS2.onload  = function()    {CLodopJsState = "complete";}
    JS1.onerror = JS2.onerror = function(evt) {CLodopJsState = "complete";}
    head.insertBefore(JS1, head.firstChild);
    head.insertBefore(JS2, head.firstChild);
    CLodopIsLocal = !!((JS1.src + JS2.src).match(/\/\/localho|\/\/127.0.0./i));
}

if (needCLodop()){loadCLodop();}//加载

//==获取LODOP对象主过程,判断是否安装、需否升级:==
function getLodop(oOBJECT, oEMBED) {
    var strHtmInstall = "<br><font color='#FF00FF'>打印控件未安装!点击这里<a href='/Public/js/install_lodop32.exe' target='_self'>执行安装</a>,安装后请刷新页面或重新进入。</font>";
    var strHtmUpdate = "<br><font color='#FF00FF'>打印控件需要升级!点击这里<a href='/Public/js/install_lodop32.exe' target='_self'>执行升级</a>,升级后请重新进入。</font>";
    var strHtm64_Install = "<br><font color='#FF00FF'>打印控件未安装!点击这里<a href='/Public/js/install_lodop64.exe' target='_self'>执行安装</a>,安装后请刷新页面或重新进入。</font>";
    var strHtm64_Update = "<br><font color='#FF00FF'>打印控件需要升级!点击这里<a href='/Public/js/install_lodop64.exe' target='_self'>执行升级</a>,升级后请重新进入。</font>";
    var strHtmFireFox = "<br><br><font color='#FF00FF'>（注意：如曾安装过Lodop旧版附件npActiveXPLugin,请在【工具】->【附加组件】->【扩展】中先卸它）</font>";
    var strHtmChrome = "<br><br><font color='#FF00FF'>(如果此前正常，仅因浏览器升级或重安装而出问题，需重新执行以上安装）</font>";
    var strCLodopInstall_1 = "<br><font color='#FF00FF'>Web打印服务CLodop未安装启动，点击这里<a href='/Public/js/CLodop_Setup_for_Win32NT.exe' target='_self'>下载执行安装</a>";
    var strCLodopInstall_2 = "<br>（若此前已安装过，可<a href='/Public/js/CLodop_Setup_for_Win32NT.exe' target='_self'>点这里直接再次启动</a>）";
    var strCLodopInstall_3 = "，成功后请刷新本页面。</font>";
    var strCLodopUpdate = "<br><font color='#FF00FF'>Web打印服务CLodop需升级!点击这里<a href='/Public/js/CLodop_Setup_for_Win32NT.exe' target='_self'>执行升级</a>,升级后请刷新页面。</font>";
    var LODOP;
    try {
        var ua = navigator.userAgent;
        var isIE = !!(ua.match(/MSIE/i)) || !!(ua.match(/Trident/i));
        if (needCLodop()) {
            try {
                LODOP = getCLodop();
            } catch (err) {}
            if (!LODOP && CLodopJsState !== "complete") {
                if (CLodopJsState == "loading") alert("网页还没下载完毕，请稍等一下再操作."); else alert("没有加载CLodop的主js，请先调用loadCLodop过程.");
                return;
            }
            if (!LODOP) {
                document.body.innerHTML = strCLodopInstall_1 + (CLodopIsLocal ? strCLodopInstall_2 : "") + strCLodopInstall_3 + document.body.innerHTML;
                return;
            } else {
                if (CLODOP.CVERSION < "4.1.1.3") {
                    document.body.innerHTML = strCLodopUpdate + document.body.innerHTML;
                }
                if (oEMBED && oEMBED.parentNode)
                    oEMBED.parentNode.removeChild(oEMBED); //清理旧版无效元素
                if (oOBJECT && oOBJECT.parentNode)
                    oOBJECT.parentNode.removeChild(oOBJECT);
            }
        } else {
            var is64IE = isIE && !!(ua.match(/x64/i));
            //==如果页面有Lodop就直接使用,否则新建:==
            if (oOBJECT || oEMBED) {
                if (isIE)
                    LODOP = oOBJECT;
                else
                    LODOP = oEMBED;
            } else if (!CreatedOKLodopObject) {
                LODOP = document.createElement("object");
                LODOP.setAttribute("width", 0);
                LODOP.setAttribute("height", 0);
                LODOP.setAttribute("style", "position:absolute;left:0px;top:-100px;width:0px;height:0px;");
                if (isIE)
                    LODOP.setAttribute("classid", "clsid:2105C259-1E0C-4534-8141-A753534CB4CA");
                else
                    LODOP.setAttribute("type", "application/x-print-lodop");
                document.documentElement.appendChild(LODOP);
                CreatedOKLodopObject = LODOP;
            } else
                LODOP = CreatedOKLodopObject;
            //==Lodop插件未安装时提示下载地址:==
            if ((!LODOP) || (!LODOP.VERSION)) {
                if (ua.indexOf('Chrome') >= 0)
                    document.body.innerHTML = strHtmChrome + document.body.innerHTML;
                if (ua.indexOf('Firefox') >= 0)
                    document.body.innerHTML = strHtmFireFox + document.body.innerHTML;
                document.body.innerHTML = (is64IE ? strHtm64_Install : strHtmInstall) + document.body.innerHTML;
                return LODOP;
            }
        }
        if (LODOP.VERSION < "6.2.2.6") {
            if (!needCLodop())
                document.body.innerHTML = (is64IE ? strHtm64_Update : strHtmUpdate) + document.body.innerHTML;
        }
        //===如下空白位置适合调用统一功能(如注册语句、语言选择等):==
        LODOP.SET_LICENSES("","358E7720F18FC5370C2154777A819C88AB3","","");



        //=======================================================
        return LODOP;
    } catch (err) {
        alert("getLodop出错:" + err);
    }
}

/**
* 打印html
*/
function lodop_print_html(title,html,printer,width,height,print_type)
{
    LODOP = getLodop();
    LODOP.PRINT_INIT(title); // 初始化
    if(printer)
    {
        // 指定打印机
        LODOP.SET_PRINTER_INDEX(printer); 
    }
    //打印纸张尺寸
    width = width + 'mm';
    
    if(height == ""){
        height = "100%"
    }else{
        height = height + 'mm'
    }
    LODOP.SET_PRINT_PAGESIZE(1,width,height,'CreateCustomPage');

    LODOP.ADD_PRINT_TABLE(0, 0,'100%','100%', html);
    if(print_type == 2){
        LODOP.SET_PRINT_STYLEA(1,'AngleOfPageInside',90)
        LODOP.SET_PRINT_MODE("PRINT_PAGE_PERCENT",'90%');
    }


    LODOP.PRINT();
}

/**
* 预览
*/
function lodop_preview_html(title,html,printer,width,height,print_type)
{
    LODOP = getLodop();
    LODOP.PRINT_INIT(title); // 初始化
    if(printer)
    {
        // 指定打印机
        LODOP.SET_PRINTER_INDEX(printer); 
    }
    
    //打印纸张尺寸
    width = width + 'mm';
    console.log(height);
    if(height == ""){
        height = "100%"
    }else{
        height = height + 'mm'
    }
    LODOP.SET_PRINT_PAGESIZE(1,width,height,'CreateCustomPage');
    
    LODOP.ADD_PRINT_TABLE(0, 0,'100%','100%', html);

    if(print_type == 2){
        LODOP.SET_PRINT_STYLEA(1,'AngleOfPageInside',90)
        LODOP.SET_PRINT_MODE("PRINT_PAGE_PERCENT",'90%');
    }
    LODOP.PREVIEW();
}

//批量打印单据
function lodop_print_htmls(title,html,printer,width,height,print_data,print_type)
{
    LODOP = getLodop();
    LODOP.PRINT_INIT(title); // 初始化
    if(printer)
    {
        // 指定打印机
        LODOP.SET_PRINTER_INDEX(printer); 
    }

    LODOP.SET_PRINT_PAGESIZE(1,width,height,'CreateCustomPage');
	for(j=0;j<print_data.length;j++){
		var goods=huodong='';
		var g_list=print_data[j].g_list;
		
		for (i=0;i<g_list.length;i++){
		        if(g_list[i].sku){
			        sku = '('+g_list[i].sku+')';
				}else{
				    sku = '';
				}
				huodong=g_list[i].prom_id!=0 ? ' (活动商品)' : '';
				goods+='<tr><td>'+(i+1)+'</td><td class="p-name">'+g_list[i].goods_name+huodong+' </td><td>'+g_list[i].spec_key_name+sku+'</td><td>nbsp;nbsp;'+parseInt(g_list[i].goods_num)+'nbsp;nbsp;</td><td>nbsp;nbsp;'+g_list[i].spu+'nbsp;nbsp;</td><td>'+g_list[i].goods_kou_price+'</td><td>￥'+g_list[i].goods_kou_total+'</td></tr>';
			}
			
		var fhtml = html.replace(/（）/g,"("+i+")");
			fhtml = fhtml.replace('jian_count',print_data[j].jian_count);
			fhtml = fhtml.replace('biaoshi_xian',print_data[j].biaoshi_xian);
			fhtml = fhtml.replace('biaoshi',print_data[j].biaoshi);
			fhtml = fhtml.replace('order_sn',print_data[j].order_sn);
			fhtml = fhtml.replace('company',print_data[j].company);
			fhtml = fhtml.replace('mobile',print_data[j].mobile);
			fhtml = fhtml.replace('full_address',print_data[j].full_address);
			fhtml = fhtml.replace('total_amount',print_data[j].total_amount);
			fhtml = fhtml.replace('store_name',print_data[j].store_name);
			fhtml = fhtml.replace('store_phone',print_data[j].store_phone);
			fhtml = fhtml.replace('user_note',user_note[j]);
			fhtml = fhtml.replace('add_time',print_data[j].add_time);
			fhtml = fhtml.replace('fast_text',print_data[j].fast_text);
			fhtml = fhtml.replace('nickname',print_data[j].nickname);
			fhtml = fhtml.replace('coupon_price',print_data[j].coupon_price);
			fhtml = fhtml.replace('g_list',goods);
    LODOP.ADD_PRINT_TABLE(0, 0,'100%','100%', fhtml);
        if(print_type == 2){
            LODOP.SET_PRINT_STYLEA(j,'AngleOfPageInside',90)
        }
	LODOP.NewPageA();
	}
    if(print_type == 2){
        LODOP.SET_PRINT_STYLEA(0,'AngleOfPageInside',90)
        LODOP.SET_PRINT_MODE("PRINT_PAGE_PERCENT",'90%');
    }
    
    LODOP.PRINT();
}
//批量预览单据
function lodop_preview_htmls(title,html,printer,width,height,print_data,print_type)
{
    LODOP = getLodop();
    LODOP.PRINT_INIT(title); // 初始化
    if(printer)
    {
        // 指定打印机
        LODOP.SET_PRINTER_INDEX(printer); 
    }

    LODOP.SET_PRINT_PAGESIZE(1,width,height,'CreateCustomPage');
	for(j=0;j<print_data.length;j++){
		var goods=huodong='';
		var g_list=print_data[j].g_list;
		
		for (i=0;i<g_list.length;i++){
		        if(g_list[i].sku){
			        sku = '('+g_list[i].sku+')';
				}else{
				    sku = '';
				}
				huodong=g_list[i].prom_id!=0 ? ' (活动商品)' : '';
				goods+='<tr><td>'+(i+1)+'</td><td class="p-name">'+g_list[i].goods_name+huodong+' </td><td>'+g_list[i].spec_key_name+sku+'</td><td>'+parseInt(g_list[i].goods_num)+'</td><td>'+g_list[i].spu+'</td><td>'+g_list[i].goods_kou_price+'</td><td>￥'+g_list[i].goods_kou_total+'</td></tr>';
			}
			
		var fhtml = html.replace(/（）/g,"("+i+")");
			fhtml = fhtml.replace('jian_count',print_data[j].jian_count);
			fhtml = fhtml.replace('biaoshi_xian',print_data[j].biaoshi_xian);
			fhtml = fhtml.replace('biaoshi',print_data[j].biaoshi);
			fhtml = fhtml.replace('order_sn',print_data[j].order_sn);
			fhtml = fhtml.replace('company',print_data[j].company);
			fhtml = fhtml.replace('mobile',print_data[j].mobile);
			fhtml = fhtml.replace('full_address',print_data[j].full_address);
			fhtml = fhtml.replace('total_amount',print_data[j].total_amount);
			fhtml = fhtml.replace('store_name',print_data[j].store_name);
			fhtml = fhtml.replace('store_phone',print_data[j].store_phone);
			fhtml = fhtml.replace('user_note',user_note[j]);
			fhtml = fhtml.replace('user_note',user_note[j]);
			fhtml = fhtml.replace('add_time',print_data[j].add_time);
			fhtml = fhtml.replace('spu',print_data[j].spu);
			fhtml = fhtml.replace('nickname',print_data[j].nickname);
			fhtml = fhtml.replace('fast_text',print_data[j].fast_text);
			fhtml = fhtml.replace('coupon_price',print_data[j].coupon_price);
			fhtml = fhtml.replace('g_list',goods);
        LODOP.ADD_PRINT_TABLE(0, 0,'100%','100%', fhtml);
        LODOP.NewPageA();
        if(print_type == 2){
            LODOP.SET_PRINT_STYLEA(j,'AngleOfPageInside',90)
        }

	}
    if(print_type == 2){
        LODOP.SET_PRINT_STYLEA(0,'AngleOfPageInside',90);
        LODOP.SET_PRINT_MODE("PRINT_PAGE_PERCENT",'90%');
    }
    
    LODOP.PREVIEW();
}

//批量打印标签
function lodop_print_htmlsb(title,html,printer,width,height,print_data)
{
	LODOP = getLodop();
	LODOP.PRINT_INIT(title); // 初始化
	if(printer)
	{
		// 指定打印机
		LODOP.SET_PRINTER_INDEXA(printer);
	}
	
	LODOP.SET_PRINT_PAGESIZE(1,width,height,'CreateCustomPage');
    // LODOP.SET_PRINT_MODE("RESELECT_ORIENT",true);
    //LODOP.SET_SHOW_MODE("BKIMG_IN_PREVIEW",1);
for(j=0;j<print_data.length;j++){
    for (i=1;i<=print_data[j].jian_count;i++){
            LODOP.NewPage();
			
        var fhtml = html.replace(/（）/g,"("+i+")");
			fhtml = fhtml.replace('erweima',print_data[j].erweima[i]);
			fhtml = fhtml.replace('myfenbu_name',print_data[j].myfenbu_name);
			fhtml = fhtml.replace('biaoshi_xian',print_data[j].biaoshi_xian);
			fhtml = fhtml.replace('fast_text',print_data[j].fast_text);
			fhtml = fhtml.replace('biaoshi',print_data[j].biaoshi);
			fhtml = fhtml.replace('jian_count',print_data[j].jian_count);
			fhtml = fhtml.replace('company',print_data[j].company);
			fhtml = fhtml.replace('order_sn',print_data[j].order_sn);
			fhtml = fhtml.replace('store_name',print_data[j].store_name);
			fhtml = fhtml.replace('shijian',print_data[j].shijian);
			fhtml = fhtml.replace('user_notes',print_data[j].user_notes);
			fhtml = fhtml.replace('spu',print_data[j].spu);
            LODOP.ADD_PRINT_HTM(0, 10,'100%','100%', fhtml);
            LODOP.SET_PRINT_MODE("FULL_HEIGHT_FOR_OVERFLOW",true);
    }
}
LODOP.SET_PRINT_MODE("PRINT_PAGE_PERCENT",'90%');
	LODOP.PRINT();
}

//批量预览标签
function lodop_preview_htmlsb(title,html,printer,width,height,print_data) //,p_num,pic_data
{
    console.log(print_data)
    LODOP = getLodop();
    LODOP.PRINT_INIT(title); // 初始化
    if(printer)
    {
        // 指定打印机
        LODOP.SET_PRINTER_INDEXA(printer);
    }

    LODOP.SET_PRINT_PAGESIZE(1,width,height,'CreateCustomPage');
    for(j=0;j<print_data.length;j++){
        for (i=1;i<=print_data[j].jian_count;i++){
            LODOP.NewPage();
            var fhtml = html.replace(/（）/g,"("+i+")");
            fhtml = fhtml.replace('erweima',print_data[j].erweima[i]);
            fhtml = fhtml.replace('myfenbu_name',print_data[j].myfenbu_name);
            fhtml = fhtml.replace('biaoshi_xian',print_data[j].biaoshi_xian);
            fhtml = fhtml.replace('xianlu',print_data[j].b1);
            fhtml = fhtml.replace('fast_text',print_data[j].fast_text);
            fhtml = fhtml.replace('quyu',print_data[j].b2);
            fhtml = fhtml.replace('xuhao',print_data[j].b3);
            fhtml = fhtml.replace('fast_flag',print_data[j].fast_flag);
            fhtml = fhtml.replace('biaoshi',print_data[j].biaoshi);
            fhtml = fhtml.replace('jian_count',print_data[j].jian_count);
            fhtml = fhtml.replace('company',print_data[j].company);
            fhtml = fhtml.replace('order_sn',print_data[j].order_sn);
            fhtml = fhtml.replace('store_name',print_data[j].store_name);
            fhtml = fhtml.replace('shijian',print_data[j].shijian);
            fhtml = fhtml.replace('user_notes',print_data[j].user_notes);
            LODOP.ADD_PRINT_HTM(0, 10,'100%','100%', fhtml);
            LODOP.SET_PRINT_MODE("FULL_HEIGHT_FOR_OVERFLOW",true);
        }
    }
    LODOP.SET_PRINT_MODE("PRINT_PAGE_PERCENT",'90%');
    LODOP.PREVIEW();
}

/*
* 获取客户端本地打印机列表
* */
function printerList(){
    LODOP = getLodop();
    var s = LODOP.GET_PRINTER_COUNT();
    var printer = Array();
    for (var i=0;i<=s;i++){
        printer.push(LODOP.GET_PRINTER_NAME(i));
    }
    return printer;

}
/**
* 获取打印机名称
*/
function lodop_get_printer_name()
{
    LODOP = getLodop();
    var iPrinterCount=LODOP.GET_PRINTER_COUNT();
    var arrList = new Array();
    for(var i=0;i<iPrinterCount;i++)
    {
        arrList.push(LODOP.GET_PRINTER_NAME(i));
    };
    return arrList;

}